{% extends "base.html" %}

{% block title %}我的学员 - 乒乓球培训管理系统{% endblock %}

{% block extra_css %}
<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --success-color: #10b981;
        --warning-color: #f59e0b;
        --danger-color: #ef4444;
        --info-color: #3b82f6;
        --gray-50: #f9fafb;
        --gray-100: #f3f4f6;
        --gray-200: #e5e7eb;
        --gray-300: #d1d5db;
        --gray-400: #9ca3af;
        --gray-500: #6b7280;
        --gray-600: #4b5563;
        --gray-700: #374151;
        --gray-800: #1f2937;
        --gray-900: #111827;
        --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
        --shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
        --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
        --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
        --shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
    }

    .page-header {
        background: var(--primary-gradient);
        color: white;
        border-radius: 16px;
        padding: 2rem;
        margin-bottom: 2rem;
        position: relative;
        overflow: hidden;
    }

    .page-header::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 200px;
        height: 200px;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
        border-radius: 50%;
        transform: translate(50%, -50%);
    }

    .page-title {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
    }

    .page-subtitle {
        font-size: 1.1rem;
        opacity: 0.9;
        margin-bottom: 0;
    }

    /* 统计卡片优化 */
    .stats-overview {
        margin-bottom: 2rem;
    }

    .stats-card {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        box-shadow: var(--shadow);
        border: 1px solid var(--gray-100);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .stats-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-lg);
    }

    .stats-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: var(--card-color);
        border-radius: 16px 16px 0 0;
    }

    .stats-card.students::before { --card-color: var(--success-color); }
    .stats-card.pending::before { --card-color: var(--warning-color); }
    .stats-card.new::before { --card-color: var(--info-color); }
    .stats-card.classes::before { --card-color: #8b5cf6; }

    .stats-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        color: white;
        margin-bottom: 1rem;
    }

    .stats-icon.students { background: var(--success-color); }
    .stats-icon.pending { background: var(--warning-color); }
    .stats-icon.new { background: var(--info-color); }
    .stats-icon.classes { background: #8b5cf6; }

    .stats-number {
        font-size: 2.25rem;
        font-weight: 700;
        color: var(--gray-900);
        margin-bottom: 0.25rem;
        line-height: 1;
    }

    .stats-label {
        font-size: 0.875rem;
        color: var(--gray-600);
        font-weight: 500;
    }

    .stats-change {
        font-size: 0.75rem;
        font-weight: 600;
        margin-top: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.25rem;
    }

    .stats-change.positive { color: var(--success-color); }
    .stats-change.negative { color: var(--danger-color); }

    /* 搜索和筛选区域 */
    .search-section {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        box-shadow: var(--shadow);
        border: 1px solid var(--gray-100);
        margin-bottom: 2rem;
    }

    .search-input-group {
        position: relative;
    }

    .search-input-group .search-icon {
        position: absolute;
        left: 1rem;
        top: 50%;
        transform: translateY(-50%);
        color: var(--gray-400);
        z-index: 5;
    }

    .search-input-group .form-control {
        padding-left: 2.75rem;
        border: 2px solid var(--gray-200);
        border-radius: 12px;
        transition: all 0.2s ease;
    }

    .search-input-group .form-control:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .view-toggle {
        background: var(--gray-100);
        border-radius: 12px;
        padding: 0.25rem;
        display: none; /* 隐藏视图切换 */
    }

    .view-toggle .btn {
        border-radius: 8px;
        padding: 0.5rem 1rem;
        border: none;
        background: transparent;
        color: var(--gray-600);
        transition: all 0.2s ease;
    }

    .view-toggle .btn-check:checked + .btn {
        background: white;
        color: #667eea;
        box-shadow: var(--shadow-sm);
    }

    /* 表格样式优化 */
    .table {
        background: white;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: var(--shadow);
        border: 1px solid var(--gray-100);
    }

    .table thead th {
        background: var(--gray-50);
        border-bottom: 2px solid var(--gray-200);
        font-weight: 600;
        color: var(--gray-700);
        padding: 1rem 0.75rem;
    }

    .table tbody td {
        padding: 1rem 0.75rem;
        border-bottom: 1px solid var(--gray-100);
        vertical-align: middle;
    }

    .table tbody tr:hover {
        background-color: var(--gray-50);
    }

    .table tbody tr:last-child td {
        border-bottom: none;
    }

    .btn-group-sm .btn {
        padding: 0.375rem 0.5rem;
        font-size: 0.875rem;
        border-radius: 6px;
    }

    .badge.bg-pink {
        background-color: #ec4899 !important;
    }

    .table-row-hover {
        background-color: var(--gray-50) !important;
        transform: scale(1.01);
        transition: all 0.2s ease;
    }

    /* 空状态优化 */
    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
        color: var(--gray-500);
    }

    .empty-state-icon {
        width: 120px;
        height: 120px;
        margin: 0 auto 2rem;
        background: var(--gray-100);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 3rem;
        color: var(--gray-400);
    }

    .empty-state h4 {
        color: var(--gray-700);
        margin-bottom: 1rem;
        font-weight: 600;
    }

    .empty-state p {
        color: var(--gray-500);
        font-size: 1.1rem;
        margin-bottom: 2rem;
        max-width: 400px;
        margin-left: auto;
        margin-right: auto;
    }

    /* 响应式优化 */
    @media (max-width: 768px) {
        .page-header {
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .page-title {
            font-size: 1.5rem;
        }

        .stats-overview .col-md-3 {
            margin-bottom: 1rem;
        }

        .table-responsive {
            font-size: 0.875rem;
        }

        .btn-group-sm .btn {
            padding: 0.25rem 0.375rem;
            font-size: 0.75rem;
        }
    }

    @media (max-width: 576px) {
        .table thead {
            display: none;
        }

        .table tbody tr {
            display: block;
            border: 1px solid var(--gray-200);
            border-radius: 8px;
            margin-bottom: 1rem;
            padding: 1rem;
        }

        .table tbody td {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--gray-100);
            padding: 0.5rem 0;
        }

        .table tbody td:before {
            content: attr(data-label);
            font-weight: 600;
            color: var(--gray-700);
        }

        .table tbody td:last-child {
            border-bottom: none;
        }
    }

    /* 加载动画 */
    .loading-skeleton {
        background: linear-gradient(90deg, #f0f0f0 25%, transparent 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: loading 1.5s infinite;
    }

    @keyframes loading {
        0% { background-position: 200% 0; }
        100% { background-position: -200% 0; }
    }

    /* 改进模态框样式 */
    .modal-content {
        border-radius: 16px;
        border: none;
        box-shadow: var(--shadow-xl);
    }

    .modal-header {
        border-bottom: 1px solid var(--gray-100);
        padding: 1.5rem;
    }

    .modal-body {
        padding: 1.5rem;
    }

    .modal-footer {
        border-top: 1px solid var(--gray-100);
        padding: 1.5rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面头部 -->
    <div class="page-header">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h1 class="page-title">我的学员</h1>
                <p class="page-subtitle">管理您的学员和师生关系</p>
            </div>
            <div class="d-flex gap-2">
                <a href="{{ url_for('coach_student.applications') }}" class="btn btn-light">
                    <i class="bi bi-inbox me-2"></i>学员申请
                    {% if stats.pending_applications > 0 %}
                        <span class="badge bg-warning ms-2">{{ stats.pending_applications }}</span>
                    {% endif %}
                </a>
            </div>
        </div>
    </div>

    <!-- 统计概览 -->
    <div class="row stats-overview" id="dashboard-stats">
        <div class="col-md-3 col-sm-6">
            <div class="stats-card students">
                <div class="stats-icon students">
                    <i class="bi bi-people"></i>
                </div>
                <div class="stats-number">{{ stats.total_students }}</div>
                <div class="stats-label">当前学员</div>
                <div class="stats-change positive">
                    <i class="bi bi-arrow-up"></i>
                    +5% 较上月
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="stats-card pending">
                <div class="stats-icon pending">
                    <i class="bi bi-clock"></i>
                </div>
                <div class="stats-number">{{ stats.pending_applications }}</div>
                <div class="stats-label">待审核申请</div>
                {% if stats.pending_applications > 0 %}
                <div class="stats-change positive">
                    <i class="bi bi-arrow-up"></i>
                    需要处理
                </div>
                {% else %}
                <div class="stats-change">
                    <i class="bi bi-check-circle"></i>
                    已全部处理
                </div>
                {% endif %}
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="stats-card new">
                <div class="stats-icon new">
                    <i class="bi bi-plus-circle"></i>
                </div>
                <div class="stats-number">{{ stats.new_applications_today }}</div>
                <div class="stats-label">今日新申请</div>
                <div class="stats-change {% if stats.new_applications_today > 0 %}positive{% endif %}">
                    <i class="bi bi-calendar-check"></i>
                    今日数据
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="stats-card classes">
                <div class="stats-icon classes">
                    <i class="bi bi-calendar-event"></i>
                </div>
                <div class="stats-number">{{ stats.classes_this_week }}</div>
                <div class="stats-label">本周课程</div>
                <div class="stats-change positive">
                    <i class="bi bi-arrow-up"></i>
                    +12% 较上周
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
        <form method="GET" action="{{ url_for('coach_student.my_students') }}" class="row align-items-center">
            <div class="col-md-10">
                <div class="search-input-group">
                    <i class="bi bi-search search-icon"></i>
                    <input type="text" class="form-control" name="search"
                           value="{{ search_keyword }}" placeholder="搜索学员姓名、电话或学员编号">
                </div>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="bi bi-search me-1"></i>搜索
                </button>
            </div>
        </form>

        {% if search_keyword %}
        <div class="mt-3 d-flex justify-content-between align-items-center">
            <small class="text-muted">搜索 "{{ search_keyword }}" 的结果</small>
            <a href="{{ url_for('coach_student.my_students') }}" class="btn btn-outline-secondary btn-sm">
                <i class="bi bi-x-lg me-1"></i>清除搜索
            </a>
        </div>
        {% endif %}
    </div>

    <!-- 学员列表 -->
    {% if students %}
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">
            学员列表
            <span class="badge bg-primary ms-2">共 {{ total }} 名学员</span>
        </h5>
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead class="table-light">
                <tr>
                    <th width="60">头像</th>
                    <th>学员信息</th>
                    <th>性别/年龄</th>
                    <th>联系方式</th>
                    <th>师生关系</th>
                    <th>统计数据</th>
                    <th width="160">操作</th>
                </tr>
            </thead>
            <tbody>
                {% for relation in students %}
                <tr>
                    <td data-label="头像">
                        <img src="{{ relation.student.photo_url or url_for('static', filename='images/default-avatar.svg') }}"
                             alt="{{ relation.student.real_name }}"
                             class="rounded-circle" style="width: 40px; height: 40px; object-fit: cover;">
                    </td>
                    <td data-label="学员信息">
                        <div>
                            <strong>{{ relation.student.real_name }}</strong>
                            <span class="badge bg-success ms-2">
                                <i class="bi bi-check-circle-fill me-1"></i>活跃
                            </span>
                        </div>
                        {% if relation.student.student_number %}
                        <small class="text-muted">学号: {{ relation.student.student_number }}</small>
                        {% endif %}
                    </td>
                    <td data-label="性别/年龄">
                        <span class="badge bg-{{ 'primary' if relation.student.gender == 'male' else 'pink' }}">
                            {{ '男' if relation.student.gender == 'male' else '女' }}
                        </span>
                        {% if relation.student.age %}
                        <div class="text-muted small">{{ relation.student.age }}岁</div>
                        {% endif %}
                    </td>
                    <td data-label="联系方式">
                        {% if relation.student.phone %}
                        <div><i class="bi bi-telephone me-1"></i>{{ relation.student.phone }}</div>
                        {% endif %}
                        {% if relation.student.email %}
                        <div class="text-muted small"><i class="bi bi-envelope me-1"></i>{{ relation.student.email }}</div>
                        {% endif %}
                    </td>
                    <td data-label="师生关系">
                        <div class="text-muted small">
                            <i class="bi bi-heart text-danger me-1"></i>
                            {{ relation.responded_at.strftime('%Y-%m-%d') if relation.responded_at else '未知' }}
                        </div>
                    </td>
                    <td data-label="统计数据">
                        <div class="row g-1 text-center">
                            <div class="col-6">
                                <div class="bg-light rounded p-1">
                                    <div class="fw-bold text-primary">12</div>
                                    <div class="small text-muted">总课程</div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="bg-light rounded p-1">
                                    <div class="fw-bold text-success">95%</div>
                                    <div class="small text-muted">出勤率</div>
                                </div>
                            </div>
                        </div>
                    </td>
                    <td data-label="操作">
                        <div class="btn-group btn-group-sm" role="group">
                            <button type="button" class="btn btn-primary"
                                    onclick="showScheduleModal({{ relation.student.id }}, '{{ relation.student.real_name }}')"
                                    title="安排课程">
                                <i class="bi bi-calendar-plus"></i>
                            </button>
                            <a href="{{ url_for('coach_student.student_detail', student_id=relation.student.id) }}"
                               class="btn btn-success" title="查看详情">
                                <i class="bi bi-eye"></i>
                            </a>
                            <button type="button" class="btn btn-outline-danger" title="解除关系"
                                    onclick="confirmRemove({{ relation.id }}, '{{ relation.student.real_name }}')">
                                <i class="bi bi-person-x"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- 分页 -->
    {% if pagination and pagination.pages > 1 %}
    <nav aria-label="学员列表分页" class="mt-4">
        <ul class="pagination justify-content-center">
            {% if pagination.has_prev %}
            <li class="page-item">
                <a class="page-link" href="{{ url_for('coach_student.my_students', page=pagination.prev_num, search=search_keyword) }}">
                    <i class="bi bi-chevron-left"></i>
                </a>
            </li>
            {% endif %}

            {% for page_num in pagination.iter_pages() %}
                {% if page_num %}
                    {% if page_num != pagination.page %}
                    <li class="page-item">
                        <a class="page-link" href="{{ url_for('coach_student.my_students', page=page_num, search=search_keyword) }}">
                            {{ page_num }}
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item active">
                        <span class="page-link">{{ page_num }}</span>
                    </li>
                    {% endif %}
                {% else %}
                <li class="page-item disabled">
                    <span class="page-link">…</span>
                </li>
                {% endif %}
            {% endfor %}

            {% if pagination.has_next %}
            <li class="page-item">
                <a class="page-link" href="{{ url_for('coach_student.my_students', page=pagination.next_num, search=search_keyword) }}">
                    <i class="bi bi-chevron-right"></i>
                </a>
            </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}

    {% else %}
    <!-- 空状态 -->
    <div class="empty-state">
        <div class="empty-state-icon">
            <i class="bi bi-people"></i>
        </div>
        {% if search_keyword %}
        <h4>未找到匹配的学员</h4>
        <p>没有找到与 "{{ search_keyword }}" 相关的学员信息</p>
        <div>
            <a href="{{ url_for('coach_student.my_students') }}" class="btn btn-primary">
                <i class="bi bi-arrow-clockwise me-2"></i>查看所有学员
            </a>
        </div>
        {% else %}
        <h4>还没有学员申请</h4>
        <p>您目前还没有学员，可以等待学员申请或主动推广您的课程</p>
        <div>
            <a href="{{ url_for('coach_student.applications') }}" class="btn btn-primary btn-lg me-2">
                <i class="bi bi-inbox me-2"></i>查看申请
            </a>
            <button type="button" class="btn btn-outline-primary btn-lg">
                <i class="bi bi-share me-2"></i>分享我的课程
            </button>
        </div>
        {% endif %}
    </div>
    {% endif %}
</div>

<!-- 确认解除关系对话框 -->
<div class="modal fade" id="removeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">解除师生关系</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="removeModalBody">
                确认要解除师生关系吗？
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmRemoveBtn">确认解除</button>
            </div>
        </div>
    </div>
</div>

<!-- 排课对话框 -->
<div class="modal fade" id="scheduleModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">安排课程</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="scheduleForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="campus_id" class="form-label">选择校区</label>
                                <select class="form-select" id="campus_id" name="campus_id" required>
                                    <option value="">请选择校区</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="table_id" class="form-label">选择球台</label>
                                <select class="form-select" id="table_id" name="table_id" required>
                                    <option value="">请先选择校区</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="start_time" class="form-label">开始时间</label>
                                <input type="datetime-local" class="form-control" id="start_time" name="start_time" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="end_time" class="form-label">结束时间</label>
                                <input type="datetime-local" class="form-control" id="end_time" name="end_time" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="price" class="form-label">课程费用</label>
                                <div class="input-group">
                                    <span class="input-group-text">¥</span>
                                    <input type="number" class="form-control" id="price" name="price"
                                           min="0" step="0.01" placeholder="0.00">
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">预计时长</label>
                                <input type="text" class="form-control" id="duration_display" readonly
                                       placeholder="请选择开始和结束时间">
                            </div>
                        </div>
                    </div>
                    <input type="hidden" id="schedule_student_id" name="student_id">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmScheduleBtn">确认安排</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentRelationId = null;
let currentStudentId = null;
let scheduleData = null;

$(document).ready(function() {
    // 加载排课数据
    loadScheduleData();

    // 搜索优化 - 实时搜索
    let searchTimeout;
    $('input[name="search"]').on('input', function() {
        clearTimeout(searchTimeout);
        const keyword = $(this).val().trim();

        if (keyword.length === 0) {
            // 清空搜索时立即刷新
            $(this).closest('form').submit();
        } else if (keyword.length >= 2) {
            // 输入2个字符以上时延迟搜索
            searchTimeout = setTimeout(() => {
                $(this).closest('form').submit();
            }, 800);
        }
    });

    // 确认解除关系
    $('#confirmRemoveBtn').click(function() {
        if (currentRelationId) {
            removeStudent(currentRelationId);
        }
        $('#removeModal').modal('hide');
    });

    // 确认排课
    $('#confirmScheduleBtn').click(function() {
        if (currentStudentId) {
            scheduleClass(currentStudentId);
        }
    });

    // 校区选择变化
    $('#campus_id').change(function() {
        updateTableOptions();
        updatePrice();
    });

    // 球台选择变化
    $('#table_id').change(function() {
        updatePrice();
    });

    // 时间选择变化
    $('#start_time, #end_time').change(function() {
        updateDuration();
        updatePrice();
    });

    // 统计卡片点击效果
    $('.stats-card').click(function() {
        $(this).addClass('card-clicked');
        setTimeout(() => {
            $(this).removeClass('card-clicked');
        }, 200);
    });

    // 模态框可访问性优化
    $('#scheduleModal, #removeModal').on('hidden.bs.modal', function () {
        $(document.activeElement).blur();
        $('body').focus();
    });

    // 表格行悬停效果
    $('.table tbody tr').hover(
        function() {
            $(this).addClass('table-row-hover');
        },
        function() {
            $(this).removeClass('table-row-hover');
        }
    );
});

// 数据加载函数
function loadScheduleData() {
    $.get('{{ url_for("coach_student.api_schedule_data") }}')
        .done(function(response) {
            if (response.success) {
                scheduleData = response;
                populateCampusOptions();
            } else {
                console.warn('排课数据加载失败');
            }
        })
        .fail(function() {
            console.error('加载排课数据失败');
        });
}

function populateCampusOptions() {
    const campusSelect = $('#campus_id');
    campusSelect.empty().append('<option value="">请选择校区</option>');

    if (scheduleData && scheduleData.campuses) {
        scheduleData.campuses.forEach(function(campus) {
            campusSelect.append(`<option value="${campus.id}">${campus.name}</option>`);
        });
    }
}

function updateTableOptions() {
    const campusId = $('#campus_id').val();
    const tableSelect = $('#table_id');

    tableSelect.empty();

    if (!campusId) {
        tableSelect.append('<option value="">请先选择校区</option>');
        return;
    }

    tableSelect.append('<option value="">请选择球台</option>');

    if (scheduleData && scheduleData.tables_by_campus[campusId]) {
        scheduleData.tables_by_campus[campusId].forEach(function(table) {
            tableSelect.append(`<option value="${table.id}" data-rate="${table.hourly_rate}">${table.name} (¥${table.hourly_rate}/小时)</option>`);
        });
    }
}

function updateDuration() {
    const startTime = $('#start_time').val();
    const endTime = $('#end_time').val();

    if (startTime && endTime) {
        const start = new Date(startTime);
        const end = new Date(endTime);

        if (end > start) {
            const diffMs = end - start;
            const diffHours = diffMs / (1000 * 60 * 60);
            $('#duration_display').val(`${diffHours.toFixed(1)} 小时`);
        } else {
            $('#duration_display').val('时间设置错误');
        }
    } else {
        $('#duration_display').val('请选择开始和结束时间');
    }
}

function updatePrice() {
    const tableSelect = $('#table_id');
    const selectedOption = tableSelect.find('option:selected');
    const hourlyRate = parseFloat(selectedOption.data('rate')) || 0;

    const startTime = $('#start_time').val();
    const endTime = $('#end_time').val();

    if (startTime && endTime && hourlyRate > 0) {
        const start = new Date(startTime);
        const end = new Date(endTime);

        if (end > start) {
            const diffMs = end - start;
            const diffHours = diffMs / (1000 * 60 * 60);
            const totalPrice = (diffHours * hourlyRate).toFixed(2);
            $('#price').val(totalPrice);
        }
    }
}

// 模态框函数
function showScheduleModal(studentId, studentName) {
    currentStudentId = studentId;
    $('#schedule_student_id').val(studentId);
    $('#scheduleModal .modal-title').text(`为 ${studentName} 安排课程`);

    // 重置表单
    $('#scheduleForm')[0].reset();
    $('#schedule_student_id').val(studentId);
    updateTableOptions();

    // 设置默认时间为明天上午9点到10点
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(9, 0, 0, 0);

    const endTime = new Date(tomorrow);
    endTime.setHours(10, 0, 0, 0);

    $('#start_time').val(formatDateTimeLocal(tomorrow));
    $('#end_time').val(formatDateTimeLocal(endTime));

    updateDuration();

    $('#scheduleModal').modal('show');
}

function confirmRemove(relationId, studentName) {
    currentRelationId = relationId;

    $('#removeModalBody').html(`
        <div class="alert alert-warning">
            <i class="bi bi-exclamation-triangle me-2"></i>
            您确定要解除与 <strong>${studentName}</strong> 的师生关系吗？
        </div>
        <p class="mb-2">解除后：</p>
        <ul class="mb-0">
            <li>该学员将不再是您的学员</li>
            <li>无法继续为该学员安排课程</li>
            <li>历史记录将被保留</li>
            <li>学员可以重新申请</li>
        </ul>
    `);

    $('#removeModal').modal('show');
}

// 操作函数
function scheduleClass(studentId) {
    const formData = {
        campus_id: $('#campus_id').val(),
        table_id: $('#table_id').val(),
        start_time: $('#start_time').val(),
        end_time: $('#end_time').val(),
        price: $('#price').val()
    };

    // 表单验证
    if (!formData.campus_id || !formData.table_id || !formData.start_time || !formData.end_time) {
        showMessage('请填写完整的课程信息', 'warning');
        return;
    }

    // 时间验证
    const startTime = new Date(formData.start_time);
    const endTime = new Date(formData.end_time);

    if (endTime <= startTime) {
        showMessage('结束时间必须晚于开始时间', 'warning');
        return;
    }

    if (startTime <= new Date()) {
        showMessage('开始时间不能早于当前时间', 'warning');
        return;
    }

    // 禁用按钮
    const submitBtn = $('#confirmScheduleBtn');
    submitBtn.prop('disabled', true).html('<i class="bi bi-hourglass-split me-2"></i>安排中...');

    $.ajax({
        url: `{{ url_for('coach_student.schedule_class', student_id=0) }}`.replace('0', studentId),
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            if (response.success) {
                showMessage('课程安排成功！', 'success');
                $('#scheduleModal').modal('hide');
                setTimeout(() => location.reload(), 1500);
            } else {
                showMessage(response.error || '安排失败', 'danger');
            }
        },
        error: function(xhr) {
            const response = xhr.responseJSON;
            showMessage(response?.error || '安排失败，请重试', 'danger');
        },
        complete: function() {
            submitBtn.prop('disabled', false).html('<i class="bi bi-check-lg me-2"></i>确认安排');
        }
    });
}

function removeStudent(relationId) {
    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        }
    });

    $.post(`{{ url_for('coach_student.remove_student', relation_id=0) }}`.replace('0', relationId))
        .done(function(response) {
            if (response.success) {
                showMessage(response.message || '师生关系已解除', 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showMessage(response.error || '操作失败', 'danger');
            }
        })
        .fail(function(xhr) {
            const response = xhr.responseJSON;
            showMessage(response?.error || '操作失败，请重试', 'danger');
        });
}

// 工具函数
function formatDateTimeLocal(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

function showMessage(message, type = 'info') {
    const alertClass = type === 'success' ? 'alert-success' :
                      type === 'warning' ? 'alert-warning' :
                      type === 'danger' ? 'alert-danger' : 'alert-info';

    const iconClass = type === 'success' ? 'check-circle' :
                      type === 'warning' ? 'exclamation-triangle' :
                      type === 'danger' ? 'exclamation-triangle' : 'info-circle';

    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 1060; min-width: 300px; max-width: 400px;" role="alert">
            <i class="bi bi-${iconClass} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    $('body').append(alertHtml);

    // 自动消失
    setTimeout(() => {
        $('.alert').not(':hover').fadeOut(300, function() {
            $(this).remove();
        });
    }, type === 'success' ? 3000 : 5000);
}

// 定期更新统计数据
setInterval(function() {
    updateDashboardStats();
}, 60000); // 1分钟更新一次

function updateDashboardStats() {
    $.get('{{ url_for("coach_student.api_dashboard_stats") }}')
        .done(function(response) {
            if (response.success) {
                const data = response.data;

                // 更新统计数字，添加动画效果
                animateNumber($('.stats-card.students .stats-number'), data.total_students);
                animateNumber($('.stats-card.pending .stats-number'), data.pending_applications);
                animateNumber($('.stats-card.new .stats-number'), data.new_applications_today);
                animateNumber($('.stats-card.classes .stats-number'), data.classes_this_week);
            }
        })
        .fail(function() {
            console.log('更新统计数据失败');
        });
}

function animateNumber($element, newValue) {
    const currentValue = parseInt($element.text()) || 0;

    if (currentValue !== newValue) {
        $({ countNum: currentValue }).animate({
            countNum: newValue
        }, {
            duration: 800,
            easing: 'swing',
            step: function() {
                $element.text(Math.floor(this.countNum));
            },
            complete: function() {
                $element.text(newValue);
            }
        });
    }
}

// 添加 CSS 类用于动画
$('<style>')
    .prop('type', 'text/css')
    .html(`
        .fade-in {
            animation: fadeInUp 0.6s ease-out forwards;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .card-hover {
            transform: translateY(-4px) !important;
            box-shadow: var(--shadow-xl) !important;
        }

        .card-clicked {
            transform: scale(0.98) !important;
        }

        .stat-hover {
            transform: translateY(-2px) !important;
            box-shadow: var(--shadow-md) !important;
        }
    `)
    .appendTo('head');
</script>
{% endblock %}